package com.xcj.springai.node;


import com.alibaba.cloud.ai.graph.OverAllState;
import com.alibaba.cloud.ai.graph.action.NodeAction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.prompt.PromptTemplate;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * ExpanderNode
 * 作用： 将原始查询（query）扩展成多个不同角度的变体。
 * 职责：
 * 构造 prompt 调用大模型（LLM）；
 * 拆分输出为多个变体（按行）；
 * 存入状态变量 expander_content。
 * 角色： 查询“扩展生成器”，提升搜索/分析的覆盖面。
 */
@Slf4j
public class ExpanderNode implements NodeAction{

    private static final Logger logger = LoggerFactory.getLogger(ExpanderNode.class);

    private static final PromptTemplate DEFAULTPROMPTTEMPLATE = new PromptTemplate("You are an expert at information retrieval and search optimization.\nYour task is to generate {number} different versions of the given query.\n\nEach variant must cover different perspectives or aspects of the topic,\nwhile maintaining the core intent of the original query. The goal is to\nexpand the search space and improve the chances of finding relevant information.\n\nDo not explain your choices or add any other text.\nProvide the query variants separated by newlines.\n\nOriginal query: {query}\n\nQuery variants:\n");

    private final ChatClient chatClient;

    private final Integer NUMBER = 3;

    public ExpanderNode(ChatClient.Builder chatClientBuilder) {
        this.chatClient = chatClientBuilder.build();
    }

    @Override
    public Map<String, Object> apply(OverAllState state) {
        String query = state.value("query", "");
        Integer expanderNumber = state.value("expander_number", NUMBER);

        String result = this.chatClient.prompt()
                .user(user -> user
                        .text(DEFAULTPROMPTTEMPLATE.getTemplate())
                        .param("number", expanderNumber)
                        .param("query", query))
                .stream()
                .content()
                .reduce("", String::concat)
                .block();  // 直接同步阻塞获取最终结果

        List<String> queryVariants = Arrays.asList(result.split("\n"));

        return Map.of("expander_content", queryVariants);
    }




}
